import { app, shell, BrowserWindow } from 'electron'
import { join } from 'path'
import { electronApp, optimizer, is } from '@electron-toolkit/utils'
import icon from '../../resources/icon.png?asset'
import { registerIpcHandlers } from './bridges'
import { closeConnections } from './db'
function createWindow() {
  // 创建浏览器窗口
  const mainWindow = new BrowserWindow({
    width: 900,
    height: 670,
    show: false,
    autoHideMenuBar: true,
    ...(process.platform === 'linux' ? { icon } : {}),
    webPreferences: {
      // 预加载脚本路径
      preload: join(__dirname, '../preload/index.js'),
      sandbox: false
    }
  })

  // 显示窗口
  mainWindow.on('ready-to-show', () => {
    mainWindow.show()
  })

  // 用系统默认浏览器打开外部链接
  mainWindow.webContents.setWindowOpenHandler((details) => {
    shell.openExternal(details.url)
    return { action: 'deny' }
  })

  // 加载页面
  if (is.dev && process.env['ELECTRON_RENDERER_URL']) {
    mainWindow.loadURL(process.env['ELECTRON_RENDERER_URL'])
  } else {
    mainWindow.loadFile(join(__dirname, '../renderer/index.html'))
  }
}

// 应用准备就绪时
app.whenReady().then(() => {
  // 注册IPC事件
  registerIpcHandlers()
  // 为Windows设置应用用户模型ID
  electronApp.setAppUserModelId('com.electron')

  // 生产环境关闭DevTools
  app.on('browser-window-created', (_, window) => {
    optimizer.watchWindowShortcuts(window)
  })

  createWindow()

  app.on('activate', function () {
    // macOS下：点击dock图标且无窗口时重新创建窗口
    if (BrowserWindow.getAllWindows().length === 0) createWindow()
  })
})

// 应用关闭时关闭数据库连接池
app.on('before-quit', async () => {
  try {
    await closeConnections()
    console.info('close all')
  } catch (error) {
    console.error('close all ERROR:', error)
  }
})

// 所有窗口关闭时退出应用（macOS除外）
app.on('window-all-closed', () => {
  if (process.platform !== 'darwin') {
    app.quit()
  }
})
